package com.mojo.concurrent.concurrent_07_pool;

import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池监控
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class MonitorThreadPool {
    public static void main(String[] args) {
        // 创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                5, // 核心线程数
                10, // 最大线程数
                1, // 线程空闲时间
                TimeUnit.SECONDS, // 空闲时间单位
                new ArrayBlockingQueue<>(10) // 任务队列
        );

        // 启动JMX监控
        startJmxMonitoring(threadPool);

        // 提交一些任务
        for (int i = 0; i < 20; i++) {
            final int taskNumber = i;
            threadPool.execute(() -> {
                System.out.println("Executing task " + taskNumber);
                try {
                    // 模拟任务执行
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 关闭线程池
        threadPool.shutdown();
    }
    private static void startJmxMonitoring(ThreadPoolExecutor threadPool) {
        // 获取MBean服务器
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

        try {
            // 注册线程池的JMX MBean
            mBeanServer.registerMBean(threadPool, new javax.management.ObjectName("com.example:type=ThreadPool,name=MyThreadPool"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
